<template>
  <div class="pet-info-page">
    <h2>我的宠物信息</h2>

    <el-button type="primary" @click="openDialog()">新增宠物</el-button>

    <el-table :data="petList" style="width: 100%; margin-top: 20px">
      <el-table-column prop="name" label="宠物名称" />
      <el-table-column prop="type" label="宠物类型" />
      <el-table-column label="图片" width="100">
            <template #default="scope">
                <img :src="scope.row.image" alt="宠物图片" style="width: 80px; height: auto;" />
            </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="sex" label="性别" />
        <el-table-column prop="health" label="健康状态" />
        <el-table-column v-if="isAdmin" prop="ownerName" label="所属用户" />
        <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deletePet(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑宠物' : '新增宠物'">
      <el-form :model="form":rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop = 'name'>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="类型" prop = 'type'>
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="狗" value="狗" />
            <el-option label="猫" value="猫" />
            <el-option label="鸡" value="鸡" />
            <el-option label="鸭" value="鸭" />
            <el-option label="鸟" value="鸟" />
            <el-option label="兔子" value="兔子" />
            <el-option label="龙" value="龙" />
            <el-option label="其他(请在备注栏备注)" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="宠物图片">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/api/pet/uploadImage"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeUpload"
            >
                <img v-if="form.image" :src="form.image" class="avatar" />
                <el-icon v-else><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="性别" prop = 'sex'>
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="公" value="公" />
            <el-option label="母" value="母" />
          </el-select>
        </el-form-item>
        <el-form-item label="健康状态" >
          <el-select v-model="form.health" placeholder="请选择健康状态">
            <el-option label="健康" value="健康" />
            <el-option label="生病" value="生病" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="form.age" :min="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary"  @click="savePet">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { storeToRefs } from 'pinia'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { computed } from 'vue'

// 判断当前用户是否是管理员
const isAdmin = computed(() => name.value === 'admin')
// 获取用户信息
const userStore = useUserStore()
const { id, name, token } = storeToRefs(userStore)

// 宠物相关数据
const petList = ref([])
const dialogVisible = ref(false)
const form = ref({
  id: null,
  name: '',
  type: '',
  image: '',
  sex: '',
  health: '',
  age: 0,
  owner: null
})
const formRef = ref(null)

const rules = {
  name: [{ required: true, message: '请输入宠物名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
}

//普通用户功能：加载自己宠物信息
const loadPets = async () => {
  if (!id.value) {
    ElMessage.error('未获取到用户信息，请重新登录')
    return
  }
  try {
    const res = await axios.get(`/api/pet/list?ownerId=${id.value}`)
    if (res.data.success) {
      petList.value = res.data.data
    } else {
      ElMessage.error('宠物列表加载失败')
    }
  } catch (e) {
    ElMessage.error('请求失败，请检查网络或登录状态')
  }
}

//管理员功能：加载所有宠物信息
const loadAllPets = async () => {
  if (!id.value) {
    ElMessage.error('未获取到用户信息，请重新登录')
    return
  }
  try {
    const res = await axios.get(`/api/pet/all?ownerId=${id.value}`)
    if (res.data.success) {
      petList.value = res.data.data
    } else {
      ElMessage.error('宠物列表加载失败')
    }
  } catch (e) {
    ElMessage.error('请求失败，请检查网络或登录状态')
  }
}

// 打开新增或编辑对话框
const openDialog = (row = null) => {
  if (row) {
    form.value = { ...row }
  } else {
    form.value = {
      id: '',
      name: '',
      type: '',
      image: '',
      sex: '',
      health: '',
      age: 0,
      owner: id.value
    }
  }
  dialogVisible.value = true
}

// 保存宠物信息
const savePet = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整信息')
      return
    }

    form.value.owner = id.value // 设置宠物主人ID

    const url = form.value.id ? '/api/pet/update' : '/api/pet/add'
    const res = await axios.post(url, form.value)
    if (res.data.success) {
      ElMessage.success(res.data.message)
      dialogVisible.value = false
      await (isAdmin.value ? loadAllPets() : loadPets())
    } else {
      ElMessage.error(res.data.message)
    }
  })
}

// 删除宠物
const deletePet = async (petId) => {
  const res = await axios.delete(`/api/pet/delete/${petId}`)
  if (res.data.success) {
    ElMessage.success('删除成功')
    await (isAdmin.value ? loadAllPets() : loadPets())
  } else {
    ElMessage.error('删除失败')
  }
}

// 图片上传成功回调
const handleImageSuccess = (res) => {
  if (res.success) {
    form.value.image = res.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImg = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImg) {
    ElMessage.error('只能上传图片')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
  }
  return isImg && isLt2M
}

// 加载用户数据（如果刷新页面）
onMounted(() => {
  userStore.loadLocalStorage()
  if (isAdmin.value) {
    loadAllPets()
  } else {
    loadPets()
  }
})

</script>


<style scoped>
.pet-info-page {
  padding: 20px;
}
</style>
